package net.lcheng.shop.utils.weixinpay;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.security.*;


/**
 * Created by LV on 2016/4/11 0011.
 * Email:LvLoveYuForever@gmail.com
 */
public class HttpRequest {
    /**
     * 请求工具类(使用httpClient)
     * @param requestUrl 请求的API的URL
     * @param postData  需要发送的内容
     * @param certPassword  证书密码
     * @throws Exception
     * @return String
     */
    public static String httpRequest(String requestUrl, String postData,String certPassword) throws Exception {

        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        /**从根路径获取证书*/
        Resource resource= new ClassPathResource("apiclient_cert.p12");

        FileInputStream inStream = new FileInputStream(resource.getFile());//加载本地的证书进行https加密传输


        keyStore.load(inStream, certPassword.toCharArray());//设置证书密码

        inStream.close();




        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, certPassword.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();

        HttpPost httpPost=new HttpPost(requestUrl);

        /**得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别*/
        StringEntity postEntity = new StringEntity(postData, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);

        //设置请求器的配置
        httpPost.setConfig(RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(3000).build());

        HttpResponse response=httpClient.execute(httpPost);
        HttpEntity entity=response.getEntity();

        return EntityUtils.toString(entity);
    }
}
